package cn.com.kblog.model;




import java.util.Calendar;
import java.util.Date;

import org.apache.commons.codec.digest.DigestUtils;

import com.jfinal.ext.plugin.tablebind.TableBind;
import com.jfinal.plugin.activerecord.Model;
@TableBind(tableName = "email_verify")
public class EmailVerify extends Model<EmailVerify> {
    
    
	private static final long serialVersionUID = -6457705494715524322L;

	public static final EmailVerify dao = new EmailVerify();

    public static final String USER_ID = "user_id";			// user id,绑定的其他的id，wbid
	public static final String VERIFY_CODE = "verify_code";	// 验证码
	public static final String CREATE_TIME = "create_time"; // 添加时间
	
	/**
	 * 根据code查找
	 * @param code
	 * @return
	 */
	public EmailVerify getByCode(String code) {
		String sql = "SELECT m.* FROM email_verify m WHERE hour(TIMEDIFF(NOW(), m.create_time)) < 24 AND m.verify_code = ? limit 1";
		return dao.findFirst(sql, code);
	}

	/**
	 * createVerify
	 * @param @return    生成的验证码
	 * @return MailVerify    返回类型
	 */
	public String createVerify( Integer userId) {
		String value = DigestUtils.md5Hex(System.currentTimeMillis() + "");
		EmailVerify Verify = new EmailVerify();
		Verify.set(EmailVerify.CREATE_TIME, new java.sql.Timestamp(Calendar.getInstance()
				.getTimeInMillis()));
		Verify.set(EmailVerify.VERIFY_CODE, value);
		Verify.set(EmailVerify.USER_ID, userId);
		if(Verify.save()){
			return value;
		}else{
			return null;
		}
	}
	
}
